<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var fourSum = function (nums, target) {
        let result = [];
        nums.sort((a, b) => a - b);
        for (let i = 0; i < nums.length; i++) {
          if (nums[i] == nums[i - 1]) {
            continue;
          }
          /* 
          有个细节在于 nums[j-1]刚开始就是nums[i] 而nums[i]是可以等于nums[j]的
          所以无需跳过   1 1 3 4 
          */
          for (let j = i + 1; j < nums.length; j++) {
            if (j > i + 1 && nums[j] == nums[j - 1]) {
              continue;
            }
            let left = j + 1;
            let right = nums.length - 1;
            /* left不能等于right 因为必须是四个数组元素 */
            while (left < right) {
              let sum = nums[i] + nums[j] + nums[left] + nums[right];
              if (sum < target) {
                left++;
              } else if (sum > target) {
                right--;
              } else {
                while (nums[left] == nums[left + 1]) {
                  left++;
                }
                while (nums[right] == nums[right - 1]) {
                  right--;
                }
                result.push([nums[i], nums[j], nums[left], nums[right]]);
                left++;
                right--;
              }
            }
          }
        }
        return result
      };
      console.log(fourSum([1, 0, -1, 0, -2, 2], 0));
    </script>
  </body>
</html>
